import {Button, Form, Row, Col, Input, Select, message, Tabs, Spin} from 'antd'
import React, {useState, useEffect, useRef} from 'react'
import {history, connect} from 'umi'
import styles from './index.less'
import {getDict} from '@/service/common/dict'
import Modal from '@/components/Modal'
import {getPublicDownloadUrl} from '@/service/common/upload'
import {editInsurance, viewInsurance} from '@/service/carMessage/insurance'
import InsuranceCard from './components/InsuranceCard'
import PurchaseRecord from './components/PurchaseRecord'

const newlyAdded = (props: any) => {
	const {query} = props.location
	const [type, setType] = useState<string>('')
	const [headerForm] = Form.useForm()
	const [basicForm] = Form.useForm()
	const InsuranceCardRef = useRef<any>(null)
	const [formData, setFormData] = useState<any>({})
	// 字典数据
	const [dictData, setDictData] = useState<any>({})
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [loading, setLoading] = useState(false)
	const [btnLoading, setBtnLoading] = useState(false)
	const [datas, setDatas] = useState()
	const [enclosureList, setEnclosureList] = useState<any[]>([])

	useEffect(() => {
		// 初始化字典数据
		getDict(
			{
				dictKeys: [
					'carStatus',
					'commercial_company_code',
					'carrier_company_code',
					'compulsory_company_code',
					'license_plate_nature',
					'buy_Type',
				],
			},
			(res: any) => {
				setDictData(res)
			},
		)
	}, [])

	// 根据路由判断当前页面状态
	useEffect(() => {
		const hrefs = window.location.href
		if (hrefs.includes('view')) {
			setType('view')
		} else {
			setType('edit')
		}
	}, [])
	useEffect(() => {
		if (query?.id) {
			setLoading(true)
			viewInsurance({id: query?.id})
				.then((res: any) => {
					if (res?.success) {
						setDatas(res?.data)
						headerForm.setFieldsValue({
							carStatus: res?.data?.carStatus?.toString(),
							operationType: res?.data?.operationType,
						})
						basicForm.setFieldsValue({
							...res?.data,
							numberType: res?.data?.numberType.toString(),
						})
						const url = [
							res?.data?.compulsoryPhotos?.[0],
							res?.data?.commercialPhotos?.[0],
							res?.data?.carrierPhotos?.[0],
						]?.map(Number)
						getPublicDownloadUrl(url)
							.then((result: any) => {
								setEnclosureList(result?.data)
							})
							.catch((err: any) => {
								message.error(err)
							})

					}
					setLoading(false)
				})
				.catch((err) => {
					message.error(err)
					setLoading(false)
				})
		}
	}, [query])

	const onSave = async () => {
		const InsuranceCardData = await InsuranceCardRef.current.getData()
		setFormData({
			id: query?.id,
			...InsuranceCardData,
		})
		setIsModalOpen(true)
	}
	const onSubmit = () => {
		setBtnLoading(true)
		editInsurance(formData)
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					history.goBack()
				}
				setBtnLoading(false)
			})
			.catch((err: any) => {
				message.error(err)
				setBtnLoading(false)
			})
	}
	const tabItem = [
		{
			label: '保险信息',
			key: '保险信息',
			children: (
				<InsuranceCard
					ref={InsuranceCardRef}
					data={datas}
					type={type}
					dictData={dictData}
					enclosureList={enclosureList}
				/>
			),
		},
		{
			label: '购买记录',
			key: '购买记录',
			children: <PurchaseRecord id={query?.id} dictData={dictData} />,
		},
	]
	return (
		<Spin spinning={loading}>
			<div className={styles.admittanceAdd}>
				<div className={styles.content}>
					<div className={styles.card}>
						<Form
							form={headerForm}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '72px'}}
							labelAlign="right"
							labelWrap
							autoComplete="off"
							disabled
						>
							<Row gutter={12} className={styles.firstLine}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 6}}
								>
									<Form.Item
										label="车辆状态"
										name="carStatus"
									>
										<Select
											placeholder="-"
											allowClear
											fieldNames={{
												value: 'dictKey',
												label: 'dictValue',
											}}
											options={dictData?.carStatus}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 6}}
								>
									<Form.Item
										label="运营分类"
										name="operationType"
									>
										<Select
											placeholder="-"
											options={[
												{value: 1, label: '自营'},
												{value: 2, label: '代运营'},
											]}
										/>
									</Form.Item>
								</Col>
							</Row>
						</Form>
						<Form
							form={basicForm}
							name="basic"
							layout="horizontal"
							labelCol={{flex: '140px'}}
							labelAlign="right"
							labelWrap
							autoComplete="off"
							disabled
						>
							<Row gutter={12}>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item
										label="所属公司"
										name="companyName"
									>
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								{}
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item label="城市" name="cityName">
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item label="持有方" name="holderName">
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item label="车辆Id" name="carId">
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item label="车架号" name="vin">
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item
										label="品牌车型车系"
										name="carBrandSeries"
									>
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item label="车牌号" name="carPlateNo">
										<Input placeholder="-" />
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item
										label="车牌性质"
										name="numberType"
									>
										<Select
											placeholder="-"
											allowClear
											fieldNames={{
												value: 'dictKey',
												label: 'dictValue',
											}}
											options={
												dictData?.license_plate_nature
											}
										/>
									</Form.Item>
								</Col>
								<Col
									sm={{span: 24}}
									md={{span: 12}}
									lg={{span: 8}}
								>
									<Form.Item
										label="发动机号"
										name="engineNumber"
									>
										<Input placeholder="-" />
									</Form.Item>
								</Col>
							</Row>
						</Form>
					</div>
					{type === 'view' ? (
						<Tabs
							type="card"
							defaultActiveKey="基础信息"
							items={tabItem}
						/>
					) : (
						<InsuranceCard
							ref={InsuranceCardRef}
							data={datas}
							type={type}
							dictData={dictData}
							enclosureList={enclosureList}
						/>
					)}

					<div className={styles.wrap}>
						{type !== 'view' ? (
							<>
								<Button
									type="primary"
									htmlType="submit"
									loading={btnLoading}
									onClick={() => {
										onSave()
									}}
								>
									保存
								</Button>
								<Button
									onClick={() => {
										history.go(-1)
									}}
								>
									关闭
								</Button>
							</>
						) : (
							''
						)}
						{type === 'view' ? (
							<Button
								onClick={() => {
									history.go(-1)
								}}
							>
								返回
							</Button>
						) : (
							''
						)}
					</div>
				</div>
				<Modal
					text="确定要保存吗？请仔细核对所填信息"
					onSubmit={onSubmit}
					isModalOpen={isModalOpen}
					setIsModalOpen={setIsModalOpen}
				/>
			</div>
		</Spin>
	)
}
export default connect(({user}: any) => ({user}))(newlyAdded)
